// middleware/auth.js
const { expressjwt: jwt } = require("express-jwt");
const secret = process.env.JWT_SECRET; // 从环境变量获取密钥

// 身份验证中间件
const authMiddleware = jwt({
  secret: secret,
  algorithms: ["HS256"],
  credentialsRequired: false, // 强制要求认证
  getToken: (req) => {
    const header = req.headers.authorization;
    if (header && header.split(" ")[0] === "Bearer") {
      return header.split(" ")[1]; // 提取 Token
    }
    return null;
  },
}).unless({ path: ['/login','/api-docs'] }); // 排除登录接口

// 错误处理中间件
const handleAuthError = (err, req, res, next) => {
  if (err.name === 'UnauthorizedError') {
    return res.status(401).json({ code: 401, message: "无效或过期的身份令牌" });
  }
  next();
};

module.exports = { authMiddleware, handleAuthError };